package Exam.view;

import Exam.controller.LoginController;
import Exam.pojo.User;
import Exam.util.MD5Util;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet(name = "LoginServlet", urlPatterns = "/login.action")
public class LoginServlet extends HttpServlet {

    private LoginController loginController = new LoginController();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");


        String username = request.getParameter("username");
        String password = request.getParameter("password");
       // String nickname = request.getParameter("nickname");
        password = MD5Util.MD5WithSalt(password);
        String verify = request.getParameter("verify");

        String text = (String) request.getSession().getAttribute("verify");

        if (text == null || !text.equalsIgnoreCase(verify)) {
            fieldMsg(request, response, "验证码错误");
            return;
        }

        User user = loginController.login(username, password);

        if (user == null) {
            // 登录失败
            fieldMsg(request, response, "用户名/密码错误");
        } else {
            // 登录成功
            HttpSession session = request.getSession();
            session.setAttribute("user", user);
            response.sendRedirect("/user/personal.jsp");
        }

    }

    private void fieldMsg(HttpServletRequest request, HttpServletResponse response, String msg) throws ServletException, IOException {
        String path = "/login.jsp";
        request.setAttribute("msg", msg);
        request.setAttribute("path", path);
        response.setStatus(302);
        response.setHeader("Refresh", "5;URL=/login.jsp");
        request.getRequestDispatcher("/msg.jsp")
                .forward(request, response);
    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
